package dd

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/spf13/cast"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/url"
	"time"
)

type LoginRsp struct {
	Success bool   `json:"success"`
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		NeedValidateCode bool `json:"need_validate_code"`
	} `json:"data"`
}

func (s *DingdongSession) Login(mobile string) error {
	Url, _ := url.Parse("https://sunquan.api.ddxq.mobi/api/user/sms/send/")

	uk := fmt.Sprintf("%x", md5.Sum([]byte(cast.ToString(time.Now().Unix()))))

	rand.Seed(time.Now().Unix())

	params := url.Values{}
	p := map[string]string{
		"sms_source":    "1",
		"pageid":        "",
		"androidid":     uk[0:15],
		"time":          cast.ToString(time.Now().Unix()),
		"longitude":     "121.537688",
		"mobile":        mobile,
		"version_code":  "94920005",
		"packag_name":   "com.yaya.zone",
		"city_number":   "0101",
		"device_id":     uk,
		"api_version":   "9.49.0",
		"app_client_id": "3",
		"latitude":      "31.264967",
		"ip":            "192.168.1.100",
		"uid":           "",
		"device_token":  "",
		"os_version":    "10.1.1",
		"seqid":         cast.ToString(rand.Int()),
		"app_type":      "normal",
		"channel":       "baidu",
		"station_id":    "5b98b0acc0a1ea8f1c8b5dc4",
		"sign":          "",
	}
	for k, v := range p {
		params.Set(k, v)
	}

	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	req, _ := http.NewRequest("POST", urlPath, nil)
	req.Header.Set("Host", "sunquan.api.ddxq.mobi")
	req.Header.Set("ddmc-city-number", "0101")
	req.Header.Set("user-agent", "Mozilla/5.0 (Linux; Android 9; LIO-AN00 Build/LIO-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/92.0.4515.131 Mobile Safari/537.36 xzone/9.47.0 station_id/null")
	req.Header.Set("accept", "application/json, text/plain, */*")
	req.Header.Set("ddmc-os-version", "undefined")
	req.Header.Set("ddmc-channel", "undefined")
	req.Header.Set("ddmc-build-version", "2.81.0")
	req.Header.Set("content-type", "application/x-www-form-urlencoded")
	req.Header.Set("ddmc-app-client-id", "3")
	req.Header.Set("ddmc-api-version", "9.49.0")
	req.Header.Set("origin", "https://wx.m.ddxq.mobi")
	req.Header.Set("x-requested-with", "com.yaya.zone")
	req.Header.Set("sec-fetch-site", "same-site")
	req.Header.Set("sec-fetch-mode", "cors")
	req.Header.Set("sec-fetch-dest", "empty")
	req.Header.Set("referer", "https://wx.m.ddxq.mobi/")
	req.Header.Set("accept-language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7")

	resp, err := s.Client.Do(req)
	if err != nil {
		return err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	var lresp LoginRsp
	if err = json.Unmarshal(body, &lresp); err != nil {
		return err
	}

	if lresp.Success == true {
		fmt.Printf("登陆返回内容：%#v\n", lresp.Data)
		return nil
	} else {
		return errors.New(lresp.Message)
	}
}
